<template>
  <div class="example-component">
    <iframe class="example-component-iframe" frameborder="0" ref="iframe"></iframe>
  </div>
</template>

<script>
export default {
  props: {
    path: {
      default: '',
      type: String,
      required: true
    },
    rawSource: {
      default: '',
      type: String,
      required: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.runCode()
    })
  },
  methods: {
    runCode(rawCode = null) {
      const codeStr = rawCode ? rawCode : decodeURIComponent(this.rawSource)
      const libDict = {
        leaflet: {
          css: 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css',
          js: 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js'
        },
        ol: {
          css: 'https://openlayers.org/en/v4.6.5/css/ol.css',
          js: 'https://openlayers.org/en/v4.6.5/build/ol.js'
        },
        mapbox: {
          css: 'https://api.mapbox.com/mapbox-gl-js/v2.14.1/mapbox-gl.css',
          js: 'https://api.mapbox.com/mapbox-gl-js/v2.14.1/mapbox-gl.js'
        },
      }
      const version = this.path.split('/')[0]
      let code = `
        <!DOCTYPE html>
        <html lang="en">
        <head>
          <meta charset="UTF-8">
          <title>run code</title>
          <style>
            html, body {
              width: 100%;
              height: 100%;
              margin: 0;
              padding: 0;
              overflow: hidden;
            }
          </style>
          <link rel="stylesheet" href="${libDict[version].css}" />
          &lt;script src="${libDict[version].js}">&lt;/script>
        </head>
        <body>
          ${codeStr}
        </body>
        </html>
      `
      code = code.replace(/&lt;/g, '<')
      const preview = this.$refs.iframe
      preview.setAttribute("srcdoc", code);
    }
  }
}
</script>

<style lang="scss" scoped>
.example-component {
  width: 100%;
  height: 25rem;
  padding: 0.4rem;
  &-iframe {
    width: 100%;
    height: 100%;
  }
}
</style>
